<template>
  <div ref="container" class="container" id="container" :style="{height:container.height + 'px',width:container.width + 'px'}">
    <!-- <img
      v-if="imgSrc"
      class="view-image"
      :src="imgSrc"
      alt="签名"
      ref="img"
      v-draggable="dr"
      width="150"
      height="150"
    /> -->
    <VueDragResize  v-if="imgSrc" class="view-image" :parentLimitation="true" :isActive="true" :w="150" :h="159" :isResizable="false" v-on:dragging="resize">
      <img
        :src="imgSrc"
        alt="签名"
        width="150"
        height="150"
      />
    </VueDragResize>
  </div>
</template>

<script>
import PDFJS from "pdfjs-dist";
import "pdfjs-dist/web/pdf_viewer.css";
PDFJS.GlobalWorkerOptions.workerSrc = "pdfjs-dist/build/pdf.worker.js";
import { PDFDocument } from 'pdf-lib';
import VueDragResize from 'vue-drag-resize'

var container;
export default {
  name: "HelloWorld",
  props: {
    imgSrc: String,
  },
  components: {
    VueDragResize,
  },
  data() {
    return {
      pdf: [],
      container: {
        width: 0,
        height: 0,
      },
      position: {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      let url =
        "http://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
      this.getPDF(url);
    });
  },
  directives: {
    // Draggable,
  },
  methods: {
    resize(newRect) {
      this.position = {
        x: newRect.left,
        y: newRect.top,
        width: newRect.width,
        height: newRect.height,
      }
      console.log('newRect', newRect)
    },
    _base64ToArrayBuffer(base64) {
      var BASE64_MARKER = ';base64,';//声明文件流编码格式
     //[RFC2045]中有规定：Base64一行不能超过76字符，超过则添加回车换行符。因此需要把base64字段中的换行符，回车符给去掉。
      var base64Index = base64.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
      var newUrl = base64.substring(base64Index).replace(/[\n\r]/g,'');
      var raw = window.atob(newUrl);//这个方法在ie内核下无法正常解析。
      var rawLength = raw.length;
      //转换成pdf.js能直接解析的Uint8Array类型
      var array = new Uint8Array(new ArrayBuffer(rawLength));
      for (let i = 0; i < rawLength; i++) {
          array[i] = raw.charCodeAt(i) & 0xff;
      }
      return array;
    },
    async modifyPdf() {
      const url = 'http://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf'
      const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
      const pdfDoc = await PDFDocument.load(existingPdfBytes)
      const pngImage = await pdfDoc.embedPng(this._base64ToArrayBuffer(this.imgSrc))
      // const pngDims = pngImage.scale(1)
      const pages = pdfDoc.getPages()
      const { x, y, width, height, pageIndex } = this.getPostion()
      const firstPage = pages[pageIndex]
      
      // console.log(this.getPostion())
      firstPage.drawImage(pngImage, {
        x,
        y,
        width,
        height,
      })

      const pdfBytes = await pdfDoc.save()
      download(pdfBytes, "demo.pdf", "application/pdf");
    },
    onPosChange(type, el, pos) {
      // console.log(type);
      // console.log(el);
      console.log(pos);
      this.position.x = pos.x
      this.position.y = pos.y
    },
    getPostion() {
      const { x, y, width, height } = this.position
      let pageIndex = 0;
      const pageHeight = this.pdf[0].height
      if (y <= pageHeight) {
        return {
          x,
          y: pageHeight - y - height,
          width,
          height,
          pageIndex: 0,
        }
      } else {
        pageIndex = 1
        while (y > (pageHeight * (pageIndex + 1))) {
          pageIndex++
        }
        return {
          x,
          y: pageHeight - (y - (pageHeight * pageIndex)) - height,
          width,
          height,
          pageIndex,
        }
      }
      // return {
      //   x,
      //   y: y - this.pdf[0].height * pageIndex - 150,
      //   width: 150,
      //   height: 150,
      // }
    },
    async getPDF(url) {
      let pdf = await PDFJS.getDocument(url).promise;
      container = container || document.querySelector("#container");
      for (let i = 0; i < pdf.numPages; i++) {
        try {
          await this.rendPDF(pdf, i);
        } catch (e) {
          // console.error(e)
        }
      }
      console.log('pdf', this.pdf)
      console.log('container', this.container)
    },
    async rendPDF(pdf, num) {
      let page = await pdf.getPage(num);
      // 设置展示比例
      let scale = 1;
      let viewport = page.getViewport(scale);
      // let pageDiv = document.createElement('div');
      // pageDiv.setAttribute('id', 'page-' + (page.pageIndex + 1));
      // pageDiv.setAttribute('style', 'position: relative');
      // container.appendChild(pageDiv);

      let canvas = document.createElement("canvas");
      // pageDiv.appendChild(canvas);
      let context = canvas.getContext("2d");
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      this.pdf.push(
        {
          width: viewport.width,
          height: viewport.height
        }
      )
      this.container.width = viewport.width;
      this.container.height = this.container.height + viewport.height;
      // this.dr.boundingRect.right = viewport.width;
      // console.log('viewport', canvas)
      // canvas.setAttribute('style', 'display: block');
      canvas.setAttribute("style", "margin: 0 auto; display: block");
      container.appendChild(canvas);
      let renderContext = {
        canvasContext: context,
        viewport: viewport,
      };

      await page.render(renderContext);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
#container {
  border: 1px solid red;
  position: relative;
  margin: 0 auto;
}
/* .previewP_main {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 10000000;
} */
.view-image {
  border: 1px solid red;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 10000000;
  margin: 0;
}
</style>
